package com.gzhryc.shared_device.oem.h5.agent.jetty;

import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.servlet.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MainServlet extends AbsHttpServlet {

	static final Logger log = Logger.getLogger(MainServlet.class);

	private static final long serialVersionUID = 1L;

	HttpHandler httpHandler;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.httpHandler = HttpHandlerFactory.readHttpHandler("com.gzhryc.shared_device.oem.h5.agent.controllers");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			String uri = req.getRequestURI();
			Resource resource = HttpHandlerFactory.execute(httpHandler, uri, req, resp, fileItemFactory);
			if (resource != null) {
				resource.export(req, resp);
			} else {
				String httpDomain = WebUtils.getHttpDomain(req);
				String clientIp = WebUtils.getClientIP(req);
				String userAgent = req.getHeader("User-Agent");
				log.warn("请求未处理，uri = {{0}}，httpDomain = {{1}}，clientIp = {{1}}，userAgent = {{1}}", uri, httpDomain, clientIp, userAgent);
			}
		} catch (Exception e) {
			log.error("请求处理错误", e);
		} finally {
			JdbcSession.clear();
		}
	}
}
